using System;
using System.Data;
using System.IO;
using MySqlConnector;

namespace LiteTools.service
{
    public class DbService
    {
        // 请使用自己的数据库连接地址，如需数据请联系作者获取
        private static string ConnectStr =
            "Server=localhost;Port=3306;Database=lite_tools;Uid=root;Pwd=testtest;Charset=utf8;";

        public static MySqlConnection GetConnection()
        {
            var combine = Path.Combine(Environment.CurrentDirectory, "db_connection.txt");
            if (File.Exists(combine))
            {
                ConnectStr = File.ReadAllText(combine);
            }

            MySqlConnection mySqlConnection;
            try
            {
                mySqlConnection = new MySqlConnection(ConnectStr);
            }
            catch (Exception)
            {
                return null;
            }

            mySqlConnection.Open();
            return mySqlConnection.State != ConnectionState.Open ? null : mySqlConnection;
        }
        
        public static MySqlConnection GetConnection(string connectionStr)
        {
            MySqlConnection mySqlConnection;
            try
            {
                mySqlConnection = new MySqlConnection(connectionStr);
                mySqlConnection.Open();
            }
            catch (Exception)
            {
                return null;
            }

            return mySqlConnection.State != ConnectionState.Open ? null : mySqlConnection;
        }
    }
}